package org.huzhp.gateway.dynamic;

import org.huzhp.gateway.core.GatewayStatus;
import org.huzhp.gateway.dynamic.route.DynamicRouteService;
import org.huzhp.gateway.dynamic.rule.DynamicRuleService;
import org.huzhp.gateway.filter.DebugGatewayFilterFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

/**
 * @Description: gateway
 * @Author: huzp
 * @CreateDate: 2020/3/13 21:46
 * @Version: 1.0
 */
@RestController
@RequestMapping
public class GatewayController {

    @Value("${spring.application.version}")
    private String version;
    @Value("${spring.application.name}")
    private String name;
    @Value("${spring.application.url}")
    private String url;

    @Autowired
    private DynamicRouteService dynamicRouteService;

    @Autowired
    private DynamicRuleService dynamicRuleService;

    @Autowired
    private CacheManager cacheManager;

    @GetMapping("/gateway/status")
    public GatewayStatus getEurekaStatus() {
        GatewayStatus gatewayStatus = new GatewayStatus();
        gatewayStatus.setVersion(version);
        gatewayStatus.setName(name);
        gatewayStatus.setUrl(url);
        return gatewayStatus;
    }

    //增加路由
    @PostMapping("/gateway/rrs")
    public Mono<ResponseEntity<Object>> add(@RequestBody RouteRuleDef def) {

        try {
            this.dynamicRouteService.add(def.getRoute().build());
            this.dynamicRuleService.add(def.getRule());
        } catch (Exception e) {
            return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
        }
        return Mono.just(ResponseEntity.ok().build());
    }

    //查询debug日志
    @GetMapping("/gateway/debug/{requestId}")
    public Mono<String> getDebugLog(@PathVariable String requestId) {
        return Mono.justOrEmpty(cacheManager.getCache(DebugGatewayFilterFactory.CACHE_USER_LOGIN_NAME).get(requestId, String.class));
    }

    @GetMapping("/hello")
    public Mono<String> hello() {

        return Mono.just("欢迎使用API Gateway");
    }
}
